<template>
  <div :class="prefixCls">
    <div :class="`${prefixCls}-wrap`" :style="{ padding: '0 80px 0 40px' }">
      <span
        :class="{
          [`${prefixCls}-prev`]: !0,
          disabled: isPrevDisabled
        }"
        @click="handlePrev"
      >
        <el-icon><ArrowLeft /></el-icon>
      </span>
      <div :class="`${prefixCls}-right`">
        <span
          :class="{
            [`${prefixCls}-next`]: !0,
            disabled: isNextDisabled
          }"
          @click="handleNext"
        >
          <el-icon><ArrowRight /></el-icon>
        </span>
        <span
          :class="{
            [`${prefixCls}-delete`]: !0,
            disabled: getTabsState.length === 1
          }"
          @click="closeAllTab"
        >
          <el-icon><CircleClose /></el-icon>
        </span>
      </div>
      <div ref="tabNavContainer" :class="`${prefixCls}-container`">
        <div ref="tabNavContent" :class="`${prefixCls}-content`" :style="getContentStyle">
          <template v-for="item in getTabsState" :key="item.query ? item.fullPath : item.path">
            <el-tag
              :closable="!(item && item.meta && item.meta.affix)"
              :name="item.query ? item.fullPath : item.path"
              :style="getStyle(item)"
              @close="closeTab(item)"
              @click="openTab(item)"
              size="large"
            >
              <!-- <svg-icon v-if="index === 0" icon-class="home" class-name="lc-header-nav-icon" /> -->
              {{ getTabTitle(item) }}
            </el-tag>
          </template>
        </div>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import { computed, ref, unref, watch, nextTick, onMounted } from 'vue';
import { CircleClose, ArrowLeft, ArrowRight } from '@element-plus/icons-vue';
import { getGlobalCls } from '@/utils/index';

import { useRouter } from 'vue-router';
import type { RouteLocationNormalized } from 'vue-router';

import { useMultipleTabStore } from '@/store/modules/multiple-tab';

const tabStore = useMultipleTabStore();
const router = useRouter();
const activeKeyRef = ref('');
const tabNavContainer = ref<HTMLDivElement>();

const tabNavContent = ref<HTMLDivElement>();

const isNextDisabled = ref(false);

const { prefixCls } = getGlobalCls('header-nav');
// x方向的偏离
const translateX = ref(0);
const getContentStyle = computed(() => {
  return {
    transform: `translateX(${translateX.value}px)`
  };
});
const isPrevDisabled = computed(() => {
  return translateX.value === 0;
});
const getTabsState = computed(() => {
  return tabStore.getTabList.filter((item) => !item.meta?.hideTab);
});
const getTabTitle = (tab: any): string => {
  return tab.meta.title;
};
const getStyle = (tab: any) => {
  return tab.path === activeKeyRef.value ? { color: 'var(--menu-text-active-color)' } : {};
};
// 更新tabs数据
watch(
  () => tabStore.getTabList.length,
  () => {
    nextTick(() => {
      handleResetLayout();
    });
  },
  {
    immediate: true
  }
);
watch(
  () => router.currentRoute.value,
  () => {
    listenerRouteChange(router.currentRoute.value);
  },
  {
    immediate: true
  }
);

// const initTabData = {
//   fullPath: '/user/staff',
//   path: '/user/staff',
//   query: {},
//   hash: '',
//   name: 'appConfigStaff',
//   params: {},
//   meta: { title: '商品单', loaded: false },
//   href: '/user/staff',
//   matched: [
//     { meta: { title: 'Root' }, name: 'Root', path: '' },
//     { meta: { title: 'home' }, name: 'home', path: '/' },
//     { meta: { title: '商品单' }, name: 'appConfigStaff', path: '/user/staff' },
//   ],
// };
// 测试多数据情况;
// const createData = () => {
//   const dataLen = 2;
//   for (let i = 0; i < dataLen; i++) {
//     const { meta, fullPath, path } = initTabData;
//     tabStore.addTab(
//       unref({
//         ...initTabData,
//         fullPath: fullPath + i,
//         path: path + i,
//         meta: {
//           ...meta,
//           title: meta.title + i,
//         },
//       }),
//     );
//   }
// };
onMounted(() => {
  // createData();
});
const openTab = (tab: any) => {
  const { currentRoute } = router;
  const { path, params = {}, query = {} } = unref(currentRoute);

  if (tab.path === path) return;

  router.push({ params, path: tab.path, query });
};

const closeTab = (tab: any) => {
  tabStore.closeTab(tab, router);
};

const closeAllTab = () => {
  if (getTabsState.value.length > 1) {
    tabStore.closeAllTab(router);
  }
};

function listenerRouteChange(route: RouteLocationNormalized) {
  const { path, meta } = route;
  const { currentActiveMenu, hideTab } = meta;
  const isHide = !hideTab ? null : currentActiveMenu;
  const p = path;
  if (activeKeyRef.value !== p) {
    activeKeyRef.value = p as string;
  }
  if (isHide) {
    const findParentRoute = router.getRoutes().find((item) => item.path === currentActiveMenu);

    findParentRoute && tabStore.addTab(findParentRoute as unknown as RouteLocationNormalized);
  } else {
    tabStore.addTab(unref(route));
  }
}

// 重新计算位置
function handleResetLayout(): void {
  const { navWrapWidth, navContentWidth } = getTabsDom();
  if (navContentWidth > navWrapWidth && tabStore.getTabList.length > 1) {
    getContentPosition('last');
  } else {
    getContentPosition();
  }
}

function getTabsDom() {
  const navWrapWidth = tabNavContainer.value?.clientWidth || 0;
  const navContentWidth = tabNavContent.value?.clientWidth || 0;
  return {
    navWrapWidth,
    navContentWidth
  };
}

function getContentPosition(type?: string) {
  const { navWrapWidth, navContentWidth } = getTabsDom();
  // 当前最大位移
  const maxTranslateX = navWrapWidth - navContentWidth;
  let currentTranslateX = 0;
  switch (type) {
    case 'last':
      translateX.value = maxTranslateX;
      break;
    case 'next':
      currentTranslateX = translateX.value - navWrapWidth;
      translateX.value = currentTranslateX < maxTranslateX ? maxTranslateX : currentTranslateX;
      break;
    case 'prev':
      currentTranslateX = translateX.value + navWrapWidth;
      translateX.value = currentTranslateX > 0 ? 0 : currentTranslateX;
      break;
    default:
      translateX.value = 0;
  }
  nextTick(() => {
    handleNextStatus();
  });
}
function handleNextStatus() {
  const { navWrapWidth, navContentWidth } = getTabsDom();
  // 原本过小不产生分页
  if (navWrapWidth > navContentWidth || translateX.value + navContentWidth <= navWrapWidth) {
    isNextDisabled.value = true;
    return;
  }
  isNextDisabled.value = false;
}

function handlePrev() {
  if (isPrevDisabled.value) {
    return;
  }
  getContentPosition('prev');
}
function handleNext() {
  if (isNextDisabled.value) {
    return;
  }
  getContentPosition('next');
}
</script>
<style lang="scss">
$prefix-cls: #{config.$namespace}-header-nav;
.#{$prefix-cls} {
  height: 44px;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  background: #eef0f4;
  &-wrap {
    width: 100%;
    box-sizing: border-box;
    padding: 0 40px;
    position: relative;
    height: 32px;
  }
  &-prev,
  &-next,
  &-delete {
    height: 32px;
    width: 32px;
    line-height: 32px;
    text-align: center;
    cursor: pointer;
    background: #fff;
    color: #555;
  }
  &-prev,
  &-next {
    position: absolute;
    left: 0;
    top: 0;
  }
  &-next {
    position: relative;
    display: inline-block;
    left: unset;
    top: unset;
  }
  &-delete {
    font-size: 16px;
  }
  &-right {
    position: absolute;
    top: 0;
    right: 0;
    left: unset;
    width: 70px;
    display: flex;
    justify-content: space-between;
  }

  &-container {
    overflow: hidden;
  }
  &-content {
    white-space: nowrap;
    position: relative;
    float: left;
    transition: transform 0.3s;
    :first-child {
      .el-tag__close {
        display: none;
      }
    }
    > .el-tag {
      margin-right: 10px;
      color: #606266;
      background: #fff;
      cursor: pointer;
      &.el-tag--large {
        height: 32px;
      }
      .el-tag__close {
        color: #606266;
        &:hover {
          color: #606266;
          background: #fff;
        }
      }
    }
  }
  .disabled {
    &.#{$prefix-cls}-prev,
    &.#{$prefix-cls}-next,
    &.#{$prefix-cls}-delete {
      color: #ccc;
      cursor: not-allowed;
    }
  }
  &-icon {
    font-size: 16px;
  }
}
</style>
